<template>
  <form class="validate-form-container">
    <slot></slot>
    <div>
      <slot name="submit"></slot>
    </div>
  </form>
</template>
<script lang="ts">
import { defineComponent, onUnmounted } from 'vue'
import { TValidateFun, TCleanFun } from '@/types/index'
import bus from '@/plugins/bus'
export default defineComponent({
  name: 'ValidateForm',
  setup() {
    // 存入校验函数
    let validateFuncArr: TValidateFun[] = []
    // 表单项校验监听
    const onValidateCallback = (data: TValidateFun) => {
      validateFuncArr.push(data)
    }
    bus.on('form-validate', onValidateCallback)

    // 存入清空函数
    let cleanFunArr: TCleanFun[] = []
    // 表单项清空监听
    const onCleanCallback = (data: TCleanFun) => {
      cleanFunArr.push(data)
    }
    bus.on('form-clean', onCleanCallback)

    // 提交 执行校验函数并返回结果
    const handleSubmit = (): boolean => {
      const valid = validateFuncArr.map((fun) => fun()).every((boo) => boo)
      return valid
    }

    // 清空
    const handleClean = (): void => {
      cleanFunArr.forEach((fun) => fun())
    }
    onUnmounted(() => {
      bus.off('form-validate', onValidateCallback)
      validateFuncArr = []
      bus.off('form-clean', onCleanCallback)
      cleanFunArr = []
    })
    return {
      handleSubmit,
      handleClean
    }
  }
})
</script>
